package bean.managed;

import entity.MasterProductionScheduleDailyEntity;
import bean.managed.util.JsfUtil;
import bean.session.MasterProductionScheduleDailyEntityFacade;

import entity.MasterProductionScheduleMonthlyEntity;
import entity.ProductPercentageQuantityEntity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.ResourceBundle;
import java.util.Vector;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.SelectItem;
import managedbean.AbstractBacking;
import org.primefaces.component.chart.series.ChartSeries;
import org.primefaces.model.chart.CartesianChartModel;

@ManagedBean (name="masterProductionScheduleDailyEntityController")
@SessionScoped
public class MasterProductionScheduleDailyEntityController extends AbstractBacking implements Serializable {


    private MasterProductionScheduleDailyEntity current;
    private DataModel items = null;
    private DataModel createItems = null;
    private DataModel monthItems = null;
    private ArrayList<MasterProductionScheduleMonthlyEntity> periodItems;
    private CartesianChartModel cartesianModel;  
    private long previousMonthOnHand = 0;
    private long classicNuts;
    private long classicFruits;
    private long premiumNuts;
    private long premiumFruits;
    
    @EJB private bean.session.MasterProductionScheduleDailyEntityFacade ejbFacade;

    public MasterProductionScheduleDailyEntityController() {
    }

    public MasterProductionScheduleDailyEntity getSelected() {
        if (current == null) {
            current = new MasterProductionScheduleDailyEntity();
        }
        return current;
    }

    private MasterProductionScheduleDailyEntityFacade getFacade() {
        return ejbFacade;
    }
    
    public int firstIndex() {
        Vector<MasterProductionScheduleDailyEntity> mps = new Vector<MasterProductionScheduleDailyEntity>();
        mps = (Vector<MasterProductionScheduleDailyEntity>) getMonthItems().getWrappedData();
        int index = 0;
        for (int i = 0; i < mps.size(); i++) {
            if (mps.get(i).getDayofProduction() == current.getDayofProduction())
                index = i;
        }
        return index;
    }
    
    public int page() {
        return firstIndex() + 1;
    }
    
    public ArrayList<MasterProductionScheduleDailyEntity> dailyMPSThisWeek() {
        ArrayList<MasterProductionScheduleDailyEntity> dailyMPS = new ArrayList<MasterProductionScheduleDailyEntity>(current.getMpsWeekly().getMpsDaily());
        return dailyMPS;
    }

    public String prepareList() {
        recreateModel();
        return "/entities/masterProductionScheduleDailyEntity/List?faces-redirect=true";
    }

    public String prepareView() {
        current = (MasterProductionScheduleDailyEntity)getItems().getRowData();
        setPreviousMonthOnHand(ejbFacade.getPreviousMonthOnHand(current.getMpsMonthly()));
        setCreateItems(getFacade().listCreateMPS(current.getMpsMonthly().getType(), current.getYearOfProduction(), current.getMpsMonthly().getMonthOfProduction(), current.getProductionType()));
        setPeriodItems(getFacade().getPeriodMPS(current.getMpsMonthly()));
        setMonthItems(getFacade().getAllDailyMPSThisMonth(current));
        createCartesianModel(current);
        return "View";
    }
    
    private void createCartesianModel(MasterProductionScheduleDailyEntity dailyMPS) {
        cartesianModel = new CartesianChartModel();  
  
        ChartSeries norm = new ChartSeries();  
        norm.setLabel("Normal"); 
        
        norm.set("",dailyMPS.getUtilizationNormal());
        
        ChartSeries ot = new ChartSeries();  
        ot.setLabel("Over Time");
        
        ot.set("",dailyMPS.getUtilizationOverTime());
        
        cartesianModel.addSeries(norm);
        cartesianModel.addSeries(ot);
    }

    public String prepareCreate() {
        current = new MasterProductionScheduleDailyEntity();
        return "Create";
    }

    public String create() {
        try {
            current.created(getLoginPerson());
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("MasterProductionScheduleDailyEntityCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }
    
    public String prepareViewFromCreate(MasterProductionScheduleMonthlyEntity mps) {
        ArrayList<MasterProductionScheduleDailyEntity> daily = new ArrayList<MasterProductionScheduleDailyEntity>(mps.getMpsDaily());
        current = daily.get(0);
        setPreviousMonthOnHand(ejbFacade.getPreviousMonthOnHand(current.getMpsMonthly()));
        setCreateItems(getFacade().listCreateMPS(current.getMpsMonthly().getType(), current.getYearOfProduction(), current.getMpsMonthly().getMonthOfProduction(), current.getProductionType()));
        setPeriodItems(getFacade().getPeriodMPS(current.getMpsMonthly()));
        setMonthItems(getFacade().getAllDailyMPSThisMonth(current));
        createCartesianModel(current);
        System.out.println("prepareViewFromCreate");
        return "demand.show();";
    }
    
    public String prepareEditFromCreate(MasterProductionScheduleMonthlyEntity mps) {
        ArrayList<MasterProductionScheduleDailyEntity> daily = new ArrayList<MasterProductionScheduleDailyEntity>(mps.getMpsDaily());
        current = daily.get(0);
        setPreviousMonthOnHand(ejbFacade.getPreviousMonthOnHand(current.getMpsMonthly()));
        setCreateItems(getFacade().listCreateMPS(current.getMpsMonthly().getType(), current.getYearOfProduction(), current.getMpsMonthly().getMonthOfProduction(), current.getProductionType()));
        setPeriodItems(getFacade().getPeriodMPS(current.getMpsMonthly()));
        setMonthItems(getFacade().getAllDailyMPSThisMonth(current));
        createCartesianModel(current);
        System.out.println("prepareEditFromCreate");
        return "demand.show();";
    }

    public String prepareEdit() {
        current = (MasterProductionScheduleDailyEntity)getItems().getRowData();
        setPreviousMonthOnHand(ejbFacade.getPreviousMonthOnHand(current.getMpsMonthly()));
        setCreateItems(getFacade().listCreateMPS(current.getMpsMonthly().getType(), current.getYearOfProduction(), current.getMpsMonthly().getMonthOfProduction(), current.getProductionType()));
        setPeriodItems(getFacade().getPeriodMPS(current.getMpsMonthly()));
        setMonthItems(getFacade().getAllDailyMPSThisMonth(current));
        createCartesianModel(current);
        return "Edit";
    }
    
    public double calculateMonthlyChangeOverTime(MasterProductionScheduleMonthlyEntity mps) {
        return getFacade().calculateMonthlyChangeOverTime(mps);
    }
    
    public String update() {
        try {
            Vector<MasterProductionScheduleDailyEntity> dailyMPS = (Vector<MasterProductionScheduleDailyEntity>) monthItems.getWrappedData();
            for (int i = 0; i < dailyMPS.size(); i++) {
                setPPQ(dailyMPS.get(i));
                dailyMPS.get(i).created(getLoginPerson());
                getFacade().edit(dailyMPS.get(i));
            }
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("MasterProductionScheduleDailyEntityUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }
    
    public void setPPQ(MasterProductionScheduleDailyEntity dailyMPS) {
        ArrayList<ProductPercentageQuantityEntity> ppq = new ArrayList<ProductPercentageQuantityEntity>(dailyMPS.getBreakdownByProduct());
        for (int i = 0; i < ppq.size(); i++) {
            if (ppq.get(i).getProduct().getProductName().equals("Classic Nutri Bar (Nuts)"))
                ppq.get(i).setQuantity(dailyMPS.getClassicNuts());
            if (ppq.get(i).getProduct().getProductName().equals("Classic Nutri Bar (Fruits)"))
                ppq.get(i).setQuantity(dailyMPS.getClassicFruits());
            if (ppq.get(i).getProduct().getProductName().equals("Premium Power Bar (Chocolate Nuts)"))
                ppq.get(i).setQuantity(dailyMPS.getPremiumNuts());
            if (ppq.get(i).getProduct().getProductName().equals("Premium Power Bar (Redcurrant Fruits)"))
                ppq.get(i).setQuantity(dailyMPS.getPremiumFruits());
        }
    }

    public String destroy() {
        current = (MasterProductionScheduleDailyEntity)getItems().getRowData();
        performDestroy();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
            return "List";
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("MasterProductionScheduleDailyEntityDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getFacade().getAllDailyMps();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    public DataModel getCreateItems() {
        return createItems;
    }

    public void setCreateItems(DataModel createItems) {
        this.createItems = createItems;
    }

    public long getPreviousMonthOnHand() {
        return previousMonthOnHand;
    }

    public void setPreviousMonthOnHand(long previousMonthOnHand) {
        this.previousMonthOnHand = previousMonthOnHand;
    }

    public DataModel getMonthItems() {
        return monthItems;
    }

    public void setMonthItems(DataModel monthItems) {
        this.monthItems = monthItems;
    }

    public long getClassicNuts() {
        return classicNuts;
    }

    public void setClassicNuts(long classicNuts) {
        this.classicNuts = classicNuts;
    }

    public long getClassicFruits() {
        return classicFruits;
    }

    public void setClassicFruits(long classicFruits) {
        this.classicFruits = classicFruits;
    }

    public long getPremiumNuts() {
        return premiumNuts;
    }

    public void setPremiumNuts(long premiumNuts) {
        this.premiumNuts = premiumNuts;
    }

    public long getPremiumFruits() {
        return premiumFruits;
    }

    public void setPremiumFruits(long premiumFruits) {
        this.premiumFruits = premiumFruits;
    }

    public ArrayList<MasterProductionScheduleMonthlyEntity> getPeriodItems() {
        return periodItems;
    }

    public void setPeriodItems(ArrayList<MasterProductionScheduleMonthlyEntity> periodItems) {
        this.periodItems = periodItems;
    }

    public CartesianChartModel getCartesianModel() {
        return cartesianModel;
    }

    public void setCartesianModel(CartesianChartModel cartesianModel) {
        this.cartesianModel = cartesianModel;
    }

    @FacesConverter(forClass=MasterProductionScheduleDailyEntity.class)
    public static class MasterProductionScheduleDailyEntityControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            MasterProductionScheduleDailyEntityController controller = (MasterProductionScheduleDailyEntityController)facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "masterProductionScheduleDailyEntityController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Long getKey(String value) {
            java.lang.Long key;
            key = Long.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Long value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof MasterProductionScheduleDailyEntity) {
                MasterProductionScheduleDailyEntity o = (MasterProductionScheduleDailyEntity) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: "+MasterProductionScheduleDailyEntityController.class.getName());
            }
        }

    }
    
    public long calculateAllQuantity() {
        //return ejbFacade.calculateAllQuantity(current);
        long allQuantity = 0;
        
        Vector<MasterProductionScheduleDailyEntity> mps = (Vector<MasterProductionScheduleDailyEntity>) monthItems.getWrappedData();
        for (int i = 0; i < mps.size(); i++) {
            ArrayList<ProductPercentageQuantityEntity> ppq = new ArrayList<ProductPercentageQuantityEntity>(mps.get(i).getBreakdownByProduct());
            for (int j = 0; j < ppq.size(); j++) {
                allQuantity = allQuantity + ppq.get(j).getQuantity();
            }
        }
        return allQuantity;
    }
    
    public long calculateClassicNuts() {
        //return ejbFacade.calculateEachProduct(current, "Classic Nutri Bar (Nuts)");
        long allQuantity = 0;
        
        Vector<MasterProductionScheduleDailyEntity> mps = (Vector<MasterProductionScheduleDailyEntity>) monthItems.getWrappedData();
        for (int i = 0; i < mps.size(); i++) {
            ArrayList<ProductPercentageQuantityEntity> ppq = new ArrayList<ProductPercentageQuantityEntity>(mps.get(i).getBreakdownByProduct());
            for (int j = 0; j < ppq.size(); j++) {
                if (ppq.get(j).getProduct().getProductName().equals("Classic Nutri Bar (Nuts)"))
                    allQuantity = allQuantity + ppq.get(j).getQuantity();
            }
        }
        return allQuantity;
    }
    
    public long calculateClassicFruits() {
        //return ejbFacade.calculateEachProduct(current, "Classic Nutri Bar (Fruits)");
        long allQuantity = 0;
        
        Vector<MasterProductionScheduleDailyEntity> mps = (Vector<MasterProductionScheduleDailyEntity>) monthItems.getWrappedData();
        for (int i = 0; i < mps.size(); i++) {
            ArrayList<ProductPercentageQuantityEntity> ppq = new ArrayList<ProductPercentageQuantityEntity>(mps.get(i).getBreakdownByProduct());
            for (int j = 0; j < ppq.size(); j++) {
                if (ppq.get(j).getProduct().getProductName().equals("Classic Nutri Bar (Fruits)"))
                    allQuantity = allQuantity + ppq.get(j).getQuantity();
            }
        }
        return allQuantity;
    }
    
    public long calculatePremiumNuts() {
        //return ejbFacade.calculateEachProduct(current, "Premium Power (Chocolate Nuts)");
        long allQuantity = 0;
        
        Vector<MasterProductionScheduleDailyEntity> mps = (Vector<MasterProductionScheduleDailyEntity>) monthItems.getWrappedData();
        for (int i = 0; i < mps.size(); i++) {
            ArrayList<ProductPercentageQuantityEntity> ppq = new ArrayList<ProductPercentageQuantityEntity>(mps.get(i).getBreakdownByProduct());
            for (int j = 0; j < ppq.size(); j++) {
                if (ppq.get(j).getProduct().getProductName().equals("Premium Power Bar (Chocolate Nuts)"))
                    allQuantity = allQuantity + ppq.get(j).getQuantity();
            }
        }
        return allQuantity;
    }
    
    public long calculatePremiumFruits() {
        //return ejbFacade.calculateEachProduct(current, "Premium Power Bar (Redcurrant Fruits)");
        long allQuantity = 0;
        
        Vector<MasterProductionScheduleDailyEntity> mps = (Vector<MasterProductionScheduleDailyEntity>) monthItems.getWrappedData();
        for (int i = 0; i < mps.size(); i++) {
            ArrayList<ProductPercentageQuantityEntity> ppq = new ArrayList<ProductPercentageQuantityEntity>(mps.get(i).getBreakdownByProduct());
            for (int j = 0; j < ppq.size(); j++) {
                if (ppq.get(j).getProduct().getProductName().equals("Premium Power Bar (Redcurrant Fruits)"))
                    allQuantity = allQuantity + ppq.get(j).getQuantity();
            }
        }
        return allQuantity;
    }
    
    public boolean checkPercentage(double utilization) {
        if (utilization > 95) {
            return true;
        } else {
            return false;
        }
    }
    
    public boolean checkAllEqual() {
        boolean equal = true;
        if (calculateAllQuantity() != current.getMpsMonthly().getPlannedQuantity())
            equal = false;
        if (calculateClassicNuts() != current.getMpsMonthly().getClassicNuts())
            equal = false;
        if (calculateClassicFruits() != current.getMpsMonthly().getClassicFruits())
            equal = false;
        if (calculatePremiumNuts() != current.getMpsMonthly().getPremiumNuts())
            equal = false;;
        if (calculatePremiumFruits() != current.getMpsMonthly().getPremiumFruits())
            equal = false;
        return equal;
    }
    
    public boolean checkEqual(long quantity1, long quantity2) {
        if (quantity1 <= quantity2)
            return true;
        else return false;
    }
    
    public void calculateUtil(MasterProductionScheduleDailyEntity dailyMPS) {
        setQuantityToPPQ(dailyMPS);
        dailyMPS.setChangeOverTime(ejbFacade.calculateDailyChangeOverTime(dailyMPS));
        ejbFacade.calculateUtil(dailyMPS);
        createCartesianModel(dailyMPS);
    }
    
    private void setQuantityToPPQ(MasterProductionScheduleDailyEntity dailyMPS) {
        ArrayList<ProductPercentageQuantityEntity> ppq = new ArrayList<ProductPercentageQuantityEntity>(dailyMPS.getBreakdownByProduct());
        for (int i = 0; i < ppq.size(); i++) {
            if (ppq.get(i).getProduct().getProductName().equals("Classic Nutri Bar (Nuts)"))
                ppq.get(i).setQuantity(dailyMPS.getClassicNuts());
            else if (ppq.get(i).getProduct().getProductName().equals("Classic Nutri Bar (Fruits)"))
                ppq.get(i).setQuantity(dailyMPS.getClassicFruits());
            else if (ppq.get(i).getProduct().getProductName().equals("Premium Power (Chocolate Nuts)"))
                ppq.get(i).setQuantity(dailyMPS.getPremiumNuts());
            else if (ppq.get(i).getProduct().getProductName().equals("Premium Power Bar (Redcurrant Fruits)"))
                ppq.get(i).setQuantity(dailyMPS.getPremiumFruits());
        }
    }
}
